import React, { useCallback, useEffect } from 'react'
import { useHistory, useLocation } from 'react-router-dom'
import { useSelector, useDispatch } from 'react-redux'

import { actionCreater } from '@/views/home/ui/cookbook'

import {
  NavBar,
  Icon
} from 'antd-mobile'

import {
  ListContainer,
  ListWrap,
  SubTitle
} from './StyledList'

const List = (props) => {
  const { goBack, push } = useHistory()
  const { state } = useLocation()
  const dispatch = useDispatch()
  const list = useSelector(state => state.getIn(['home', 'list']))

  const handleLeftClick = useCallback(
    () => {
      goBack()
    },
    [goBack],
  )

  const handleGotoDetail = useCallback(
    (id) => {
      return () => {
        push({ pathname: '/detail', state: { id } })
      }
    },
    [push]
  )

  useEffect(() => {
    if (list.length === 0) {
      const { loadDataForSaga } = actionCreater
      dispatch(loadDataForSaga())
    }
  }, [dispatch, list])

  return (
    <ListContainer>
      <NavBar
        mode="dark"
        icon={<Icon type="left" />}
        onLeftClick={handleLeftClick}
        style={{backgroundColor: '#ee742f' }}
      >
        {state.title}
      </NavBar>
      <ul>
        {
          list.map((item, index) => {
            return (
              <ListWrap
                width="0 0 1px 0"
                key={item.id + index}
                onClick={handleGotoDetail(item.id)}
              >
                <div>
                  <img src={item.img} width="115" height="75" alt=""/>
                </div>
                <div>
                  <h1>{item.name}</h1>
                  <SubTitle>{item.burdens}</SubTitle>
                  <h3>{item.all_click}浏览 {item.favorites}收藏</h3>
                </div>
              </ListWrap>
            )
          })
        }
      </ul>
    </ListContainer>
  )
}

export default List
